package org.charless.skeleton.dao;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.charless.skeleton.bo.User;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

@Repository("UserDAO")
public class UserDao extends HibernateDaoSupport {

    public UserDao() {}
    
    /**
     * Add a new user in the database if it does not exists yet (based on its id),
     * or update the information if it exists
     * @param user The user model object
     */
    public void saveOrUpdate(User user) {
    	getHibernateTemplate().saveOrUpdate( user );
    	getHibernateTemplate().flush();
    }
    
    /**
     * Load a user from database
     * @param id
     * @return
     */
    public User load(Integer id) {
    	return (User) getHibernateTemplate().load( User.class, id);
    }
    
    /**
     * Return all registered users
     * @return The list of all users
     */
    @SuppressWarnings("unchecked")
    public List<User> findAll() {
    	return getHibernateTemplate().find("from User order by name asc");
    }
    
    /**
     * Get a user by its name
     * @param name The name of the user
     * @return The user model object, null if no user found
     */
    @SuppressWarnings("unchecked")
	public User getByName ( final String name ) {
    	return (User) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) {
				Query query = getSession().getNamedQuery("User.byName");
				query.setParameter("name", name);
				List<User> users = new ArrayList<User>( query.list() );
				if (users.size() == 0) {return null ;}
				return users.get(0);
			}
		});
    }
    
    @Resource(name="sessionFactory")
    public void setMySessionFactory(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}
    
}
